package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	var head, tail *ListNode
	carry, sum := 0, 0
	for l1 != nil || l2 != nil {
		n1, n2 := 0, 0
		if l1 != nil {
			n1 = l1.Val
			l1 = l1.Next
		}
		if l2 != nil {
			n2 = l2.Val
			l2 = l2.Next
		}
		sum, carry = (n1+n2+carry)%10, (n1+n2+carry)/10
		if head == nil {
			head = &ListNode{sum, nil}
			tail = head
		} else {
			(*tail).Next = &ListNode{sum, nil}
			tail = (*tail).Next
		}

	}
	if carry > 0 {
		(*tail).Next = &ListNode{carry, nil}
	}

	return head

}

func main() {
	fmt.Println(addTwoNumbers(&ListNode{5, nil}, &ListNode{4, nil}))
}
